/**
 * gif 转换为jpg
 * @type {sharp | ((input?: (Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string), options?: sharp.SharpOptions) => sharp.Sharp) | ((options?: sharp.SharpOptions) => sharp.Sharp)}
 */
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const sizeOf = require("image-size")
const fileUtil = require('./utils/file-util')

// 图片目录
const imagesDir = 'E:/temp/abs/images';
// 输出目录
const outputDir = 'E:/temp/abs/out';
fileUtil.clearDirectory(outputDir)

// 读取目录下所有文件的大小
fs.readdir(imagesDir, (err, files) => {
    if (err) throw err;
    files.forEach(file => {
        const filePath = path.join(imagesDir, file);
        const stats = fs.statSync(filePath);
        const fileSizeInBytes = stats["size"];
        const dimensions = sizeOf(filePath)
        console.log(file, fileSizeInBytes, dimensions, filePath)
        if(dimensions.type=='gif') {
            let file2 = file.replace('.gif', '.jpg')
            console.log('AAA', file2, filePath)
            sharp(filePath)
                .toFormat('jpg')
                //.jpeg({ quality: 40 }) // 设置压缩后的图片尺寸
                .toFile(path.join(outputDir, file2))
                .then(() => {
                    console.log(`${file2} was converted.`);
                })
                .catch(err => {
                    console.error(`An error occurred while converted ${file2}: ${err}`);
                });
        } else {
            sharp(filePath)
                .toFile(path.join(outputDir, file))
                .then(() => {
                    console.log(`${file} was moved.`);
                })
                .catch(err => {
                    console.error(`An error occurred while moved ${file}: ${err}`);
                });
        }
    });
});
